package com.hxk.di.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;

import javax.sql.DataSource;

/**
 * 使用@Profile实现多种环境，载入不同的对象实例注册到IOC容器中
 * 比如：测试环境加入测试环境的数据源，开发环境加入开发环境的数据源，生成环境加入生成环境的数据源
 */
@PropertySource("classpath:/db.properties")
@Configuration
public class MainConfigProfile implements EmbeddedValueResolverAware {


    @Value("${db.user}")//从db.properties配置文件中获取值并赋值给user
    private String user;

    private String driverClass;

    /**
     * 测试环境的数据源
     * @return
     */
    @Profile("test")
    @Bean
    public DataSource testDataSource(@Value("${db.password}") String password) throws Exception{
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driverClass);
        dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test");
        dataSource.setUser(user);
        dataSource.setPassword(password);
        return dataSource;
    }


    /**
     * 开发环境的数据源
     * @return
     */
    @Profile("dev")
    @Bean
    public DataSource devDataSource(@Value("${db.password}") String password)throws Exception{
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driverClass);
        dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test");
        dataSource.setUser(user);
        dataSource.setPassword(password);
        return dataSource;
    }


    /**
     * 生产环境的数据源
     * @return
     */
    @Profile("pord")
    @Bean
    public DataSource pordDataSource(@Value("${db.password}") String password)throws Exception{
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driverClass);
        dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test");
        dataSource.setUser(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * 使用配置文件解析器获取配置信息
     * @param stringValueResolver
     */
    @Override
    public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
        this.driverClass = stringValueResolver.resolveStringValue("${db.driverclass}");
    }
}
